package cn.alise.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.xml.security.utils.Base64;
/**
 * 图片处理工具类
 *
 */
public class ImageUtils {

	/**
	 * 从网络上下载图片，并转换为base64位的字符串
	 * @param destUrl
	 * @return
	 */
	public static String getImageString(String destUrl) {
		
		InputStream in = null;
		HttpURLConnection conn = null;
		String str = null;
	
		ByteArrayOutputStream bis = new ByteArrayOutputStream();
		try {
			URL url = new URL(destUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.connect();
			in = conn.getInputStream();
			
			int rc = 0; byte[] buf = new byte[1024];
	        while ((rc = in.read(buf, 0, 100)) > 0) {  
	        	bis.write(buf, 0, rc);  
	        }
	        
	        str = Base64.encode(bis.toByteArray());
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				
				conn.disconnect();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return str;
	}

	/**
	 * 获取base64图片数据
	 * @param imgUrl
	 * @return
	 */
	public static String getBase64Img(String imgUrl) {
		byte[] imgbyte = ImgConvertByteArray.img2byteArray(imgUrl);
		if(imgbyte == null) return "";
		return org.apache.commons.net.util.Base64.encodeBase64String(imgbyte);
	}
}
